//
//  ERMoreVC.m
//  EnjoyRunning
//
//  Created by ljm on 2017/4/19.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "ERMoreVC.h"
#import "ERPersonalDataVC.h"
#import "ERSettingVC.h"
#import "ERClearCacheVC.h"
#import "ERFeedBackVC.h"
#import "ERAboutUsVC.h"

@interface ERMoreVC ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView *myTableView;

@end

@implementation ERMoreVC

#pragma mark -- 设置navigation导航条
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBarTintColor:
     [UIColor whiteColor]];
    [self.navigationController.navigationBar
     setTitleTextAttributes:@{NSForegroundColorAttributeName:
                                  [UIColor blackColor]}];
    
//    
//    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
//    [leftBtn setImage:[UIImage imageNamed:@"mine_normal"] forState:UIControlStateNormal];
//    UIBarButtonItem *selfLeftImage = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
//    self.navigationItem.leftBarButtonItem = selfLeftImage;
//    
    //right
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 30)];
    [rightBtn setTitle:@"退出"
              forState:UIControlStateNormal];
    [rightBtn setTitleFont:FontNameAlNile
                      size:12];
    [rightBtn setTitleColor:[UIColor blackColor]];
    
    UIBarButtonItem *selfRightImage = [[UIBarButtonItem alloc]
                                       initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = selfRightImage;
    
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
  
    [self setupUI];
}

- (void)setupUI
{
//    ERBaseVC *rootVC = [[ERBaseVC alloc] init];
    self.view.backgroundColor = rootVC.view.backgroundColor;
    
    self.myTableView.backgroundColor = rootVC.view.backgroundColor;
    [self.view addSubview:self.myTableView];
}

#pragma mark -- datasource 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.000001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return kheight * 0.3;
    }else
    {
        return 40;
    }
}

#pragma mark -- UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"myCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]
                initWithStyle:
            UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    
    /*
     *    小箭头
     */
    if (indexPath.section != 0) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    switch (indexPath.section) {
        case 0:
        {
            /*
             *    用户名和背景图片
             */
//            cell.imageView.image = [UIImage imageNamed:@"mine_normal"];
//            cell.textLabel.text = @"跑步等级";
//            cell.backgroundColor = [UIColor lightGrayColor];
            
            UIImageView *myImage = [[UIImageView alloc] initWithFrame:
                                    CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, kheight * 0.3)];
            myImage.image = [UIImage imageNamed:@"s-3"];
            [cell addSubview:myImage];
            
            /*
             *    用户头像
             */
            UIButton *myIconBtn = [[UIButton alloc] initWithFrame:
                                   CGRectMake(
                                              0, 0, cell.frame.size.width * 0.25, cell.frame.size.width *0.25)];
            
            myIconBtn.center =CGPointMake(
                                          cell.frame.size.width/2, cell.frame.origin.y + kheight * 0.12);
            myIconBtn.layer.cornerRadius = myIconBtn.frame.size.width/2;
            myIconBtn.layer.masksToBounds = YES;
            [myIconBtn setImage:[UIImage imageNamed:@"s-1"]
                       forState:UIControlStateNormal];
            myIconBtn.tag = 1000;
            
            [myIconBtn addTarget:self
                          action:@selector(changeUserInfo:) forControlEvents:UIControlEventTouchUpInside];
            [myImage addSubview:myIconBtn];
            
            /*
             *    用户名
             */
            UIButton *myNameBtn = [[UIButton alloc] initWithFrame:
                                   CGRectMake(
                                              0, 0, myIconBtn.frame.size.width, 30)];
            
            myNameBtn.center = CGPointMake(
                                           cell.frame.size.width/2, myIconBtn.frame.origin.y + myIconBtn.frame.size.height + kheight * 0.05);
            [myNameBtn setTitle:@"用户名" forState:UIControlStateNormal];
            myNameBtn.tag = 1001;
            [myNameBtn addTarget:self
                          action:@selector(changeUserInfo:) forControlEvents:UIControlEventTouchUpInside];
            [myNameBtn setTitleColor:[UIColor whiteColor]];
            [myNameBtn setTitleFont:FontNameAlNile size:12];
            [myImage addSubview:myNameBtn];
            
        }
            break;
        case 1:
        {
            /*
             *    个人资料
             */
            cell.imageView.image = [UIImage imageNamed:@"mine_normal"];
            cell.textLabel.text = @"个人资料";
        }
            break;
        case 2:
        {
            /*
             *    设置
             */
            cell.imageView.image = [UIImage imageNamed:@"mine_normal"];
            cell.textLabel.text = @"设置";
        }
            break;
            
        case 3:
        {
            /*
             *    清理缓存
             */
            cell.imageView.image = [UIImage imageNamed:@"mine_normal"];
            cell.textLabel.text = @"清理缓存";
        }
            break;
            
        case 4:
        {
            /*
             *    意见反馈
             */
            cell.imageView.image = [UIImage imageNamed:@"mine_normal"];
            cell.textLabel.text = @"意见反馈";
        }
            break;
            
        case 5:
        {
            /*
             *    关于我们
             */
            cell.imageView.image = [UIImage imageNamed:@"mine_normal"];
            cell.textLabel.text = @"关于我们";
        }
            break;
        default:
            break;
    }
    
    
    return cell;
}

#pragma mark -- actions
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            /*
             *    点击背景图片
             */
            
        }
            break;
        case 1:
        {
            /*
             *    点击个人资料
             */
            ERPersonalDataVC *personalDataVC = [[ERPersonalDataVC alloc] init];
            personalDataVC.title = @"个人资料";
            
            [self.navigationController pushViewController:personalDataVC
                                                 animated:YES];
        }
            break;
            
        case 2:
        {
            /*
             *    设置
             */
            ERSettingVC *settingVC = [[ERSettingVC alloc] init];
            settingVC.title = @"个人设置";
            [self.navigationController pushViewController:settingVC
                                                 animated:YES];
        }
            break;
            
        case 3:
        {
            
            __weak typeof(self) weakself = self;
            /*
             *    清理缓存
             */
            UIAlertController *alertVC = [UIAlertController
                                          alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"是否清除%.fM缓存",[self filePath]] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sureVC = [UIAlertAction
                                     actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                /*
                 *    确定
                 */
                if ([weakself filePath] != 0) {
                    [weakself clearFile];
                    NSLog(@"--------缓存清除成功----------");
                }
                
            }];
            UIAlertAction *cancelVC = [UIAlertAction
                                       actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                /*
                 *    取消
                 */
                
            }];
            
            [alertVC addAction:sureVC];
            [alertVC addAction:cancelVC];
            
            [self presentViewController:alertVC
                               animated:YES
                             completion:^{
                
            }];
        }
            break;
        
         case 4:
        {
            /*
             *    意见反馈
             */
            ERFeedBackVC *feedbackVC = [[ERFeedBackVC alloc] init];
            feedbackVC.title = @"意见反馈";
            [self.navigationController pushViewController:feedbackVC
                                                 animated:YES];
            
        }
            break;
        
        case 5:
        {
            /*
             *    关于我们
             */
            ERAboutUsVC *aboutusVC =[[ERAboutUsVC alloc] init];
            aboutusVC.title = @"关于我们";
            [self.navigationController pushViewController:aboutusVC
                                                 animated:YES];
        }
            break;
            
        default:
            break;
    }
}


#pragma mark -- change userimage 、username
- (void)changeUserInfo:(UIButton *)btn
{
    switch (btn.tag) {
        case 1000:
        {
            /*
             *    修改头像
             */
        }
            break;
            
        default:
        {
            /*
             *    修改用户名
             */
            
        }
            break;
    }
}

#pragma mark - 清理缓存
/*
 * 1.显示缓存大小
 */
- (CGFloat)filePath {
    
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains
                          (NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    return [self folderSizeAtPath:cachPath];
}
//遍历文件获得文件大小，单位M
- (CGFloat)folderSizeAtPath:(NSString *)folderPath {
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) {
        return 0;
    }
    
    NSEnumerator *enumerator = [[manager subpathsAtPath:
                                 folderPath] objectEnumerator];
    
    NSString *fileName;
    NSInteger folderSize = 0;
    
    while ((fileName = [enumerator nextObject]) != nil) {
        
        NSString *fileAbsolutePath = [folderPath
                                      stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize / (1024.0 * 1024);
}
//计算单个文件大小
- (NSInteger)fileSizeAtPath:(NSString *)filePath {
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager
                 attributesOfItemAtPath:filePath
                 error:nil]
                fileSize];
    }
    return 0;
}

- (void)clearFile {
    //找到沙盒中存放缓存数据的文件夹路径
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains
                          (
                           NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    NSArray *files = [[NSFileManager defaultManager]
                      subpathsAtPath:
                      cachPath];
    
    [files enumerateObjectsUsingBlock:^(
                                        id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //
        NSError *error = nil;
        
        NSString *path = [cachPath stringByAppendingPathComponent:obj];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }];
    
    [self performSelectorOnMainThread:@selector(clearCachSuccess)
                           withObject:nil
                        waitUntilDone:YES];
}

/*
 *    清理成功
 */
- (void)clearCachSuccess
{
    
}

#pragma mark -- getter
- (UITableView *)myTableView
{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:
                        CGRectMake(
                                   0, 64, kwidth, kheight * 0.8)
                                                    style:UITableViewStyleGrouped];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
    }
    return _myTableView;
}

@end
